/**
 * 利用 redux 实现 count demo
 */
import React from "react"

import store from "@/redux/store"
import {incrementAction, decrementAction, incrementAsyncAction} from "@/redux/actions/count.action"

import {Button, Select} from "antd"

const {Option} = Select;

export default class CountWithRedux extends React.Component {

  state = {
    currentValue: 1
  }

  componentDidMount() {
    // 检测store状态变化
    store.subscribe(() => {
      this.setState({}) // 利用更新空的state实现调用render
    })
  }

  /**
   * 获取当前的步长
   * @param value
   */
  handleChange = (value) => {
    this.setState({currentValue: value})
  }
  /**
   * 加
   */
  increment = () => {
    let {currentValue} = this.state
    store.dispatch(incrementAction(currentValue)) // 更新状态
  }
  /**
   * 减
   */
  decrement = () => {
    let {currentValue} = this.state
    store.dispatch(decrementAction(currentValue)) // 更新状态
  }
  /**
   * 奇数加
   */
  incrementIfOdd = () => {
    let {currentValue} = this.state
    if (store.getState() % 2 !== 0) {
      store.dispatch(incrementAction(currentValue)) // 更新状态
    }
  }
  /**
   * 异步加
   */
  incrementAsync = () => {
    let {currentValue} = this.state
    store.dispatch(incrementAsyncAction(currentValue, 500)) // 更新状态
  }

  render() {
    return (
        <div>
          <h4>当前求和为：{store.getState().count}</h4>
          <Select defaultValue="1" onChange={this.handleChange}>
            <Option value="1">1</Option>
            <Option value="2">2</Option>
            <Option value="3">3</Option>
          </Select>
          &nbsp;
          <Button type="primary" size="small" onClick={this.increment}>+</Button>
          &nbsp;
          <Button type="primary" size="small" onClick={this.decrement}>-</Button>
          &nbsp;
          <Button type="primary" size="small" onClick={this.incrementIfOdd}>当前求和为奇数时再加</Button>
          &nbsp;
          <Button type="primary" size="small" onClick={this.incrementAsync}>异步加</Button>
        </div>
    )
  }
}